package com.jhx.video.publish

import android.annotation.SuppressLint
import android.app.Activity
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.jhx.common.cache.SimpleCache
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.model.Event
import com.jhx.common.model.Video
import com.jhx.common.thirdparty.db.DBHelper
import com.jhx.common.utils.customToast
import com.jhx.common.widget.CommonDialog
import com.jhx.video.R
import com.jhx.video.videoupload.TXUGCPublishTypeDef
import kotlinx.android.synthetic.main.fragment_publish_video.*
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * 发布页面
 *
 * @author Jack 2018-03-08 18:51
 */
class VideoPublishFragment : QuickBaseFragment(), Contract.PublishView {
    private var mDuration: Long? = 0L
    private var mCoverPath: String? = null
    private var mVideoPath: String? = null
    private var mDialog: CommonDialog? = null
    private var mVideo: Video? = null
    private var mFromPage: String? = null
    private var mTextContent: String? = null
    private var mPresenter: PublishPresenterImpl? = null
    private val mVideoList: ArrayList<Video> = ArrayList()

    companion object {
        val KEY_FROM = "form_page"
        val VIDEO_DATA = "video_data"
    }

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_publish_video, container, false)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mFromPage = arguments?.getString(KEY_FROM)
        mVideo = arguments.getSerializable(VIDEO_DATA) as Video
        mCoverPath = if(!TextUtils.isEmpty(mVideo?.cover_url)) mVideo?.cover_url else SimpleCache.get(Video.COVER_PATH)
        mVideoPath = mVideo?.video_url
        mDuration = mVideo?.countTime
        mTextContent = mVideo?.context
        mPresenter = PublishPresenterImpl()
        mPresenter?.setView(this)
        txt_publish.setOnClickListener {
            mPresenter?.getSign()
        }
        val file = File("${mVideo?.cover_url}")
        if(file.exists()) {
            Glide.with(activity).load(file).into(videoview)
        }
        setTitle("发布视频")
        if(TextUtils.isEmpty(mFromPage)) {
            setMenuText("保存草稿")
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun hideLoading() {
        hideLoadingDialog()
    }

    override fun getSignSuccess(sign: String?) {
        mPresenter?.publishVideo(sign, mCoverPath, mVideoPath)
    }

    override fun publishSuccess(result: TXUGCPublishTypeDef.TXPublishResult?) {
        delVideo()
        mPresenter?.reportServer(edit_desc.text.toString(),
                result?.videoURL,
                result?.coverURL,
                result?.videoId,
                mDuration?.toString())
    }

    override fun getVideoList(list: List<Video>?) {
        mVideoList.clear()
        if(list != null && list.isNotEmpty()) {
            mVideoList.addAll(list)
        }
    }

    override fun reportServerSuccess() {
        val view = LayoutInflater.from(activity).inflate(R.layout.view_toast, null)
        val msgText = view.findViewById<TextView>(R.id.txt_message)
        val statusImage = view.findViewById<ImageView>(R.id.img_status)
        msgText.text = "发布成功~"
        statusImage.setImageDrawable(resources.getDrawable(R.mipmap.img_publish_success))
        activity.customToast(view)
        val event = Event()
        event.code = Video.CODE_POST_SUCCESS
        EventBus.getDefault().post(event)
        Handler().postDelayed({
            pop()
        }, 1000)
    }

    override fun getContext(): Activity? {
        return activity
    }

    override fun publishError(code: Int, msg: String?) {
        val view = LayoutInflater.from(activity).inflate(R.layout.view_toast, null)
        val msgText = view.findViewById<TextView>(R.id.txt_message)
        val statusImage = view.findViewById<ImageView>(R.id.img_status)
        msgText.text = "发布失败，请稍后重试~"
        statusImage.setImageDrawable(resources.getDrawable(R.mipmap.img_publish_error))
        activity.customToast(view)
        Handler().postDelayed({
            pop()
        }, 1000)
    }

    /**
     * 删除视频文件
     */
    private fun delVideo() {
        val delTask = @SuppressLint("StaticFieldLeak")
        object : AsyncTask<Void, String, Void>() {
            override fun doInBackground(vararg params: Void?): Void? {
                val result = DBHelper.queryAll(Video::class.java)
                SimpleCache.delete(Video.COVER_PATH)
                val coverFile = File("$mCoverPath")
                if (coverFile.exists()) {
                    coverFile.delete()
                }
                if (result.isNotEmpty()) {
                    result.filter { it.video_url == mVideoPath }
                            .map {
                                DBHelper.delData(Video::class.java, it)
                                if (!checkbox_save.isChecked) {
                                    val videoFile = File("$mVideoPath")
                                    if (videoFile.exists()) {
                                        videoFile.delete()
                                    }
                                }
                            }
                }
                return null
            }
        }
        delTask.execute()
    }

    override fun interceptionBack(): Boolean {
        return true
    }

    override fun onBackPressed() {
        if (!TextUtils.isEmpty(mFromPage) && mTextContent == edit_desc.text.toString()) {
            pop()
            return
        }
        if(mDialog == null && !activity.isFinishing) {
            mDialog = CommonDialog(activity)
        }
            mDialog?.setTitle("是否放弃发布？")
            mDialog?.setCancelBtn("保存草稿")
            mDialog?.setConfirmBtn("返回编辑")
            mDialog?.setOnClickListener(object: CommonDialog.OnClickListener {
                override fun onConfirmClick(view: View?) {
                    pop()
                }

                override fun onCancelClick(view: View?) {
                    saveVideo()
                }

            })
            if(mDialog?.isShowing == false && !activity.isFinishing) {
                mDialog?.show()
            }
    }

    override fun showToolbar(): Boolean {
        return true
    }

    override fun onMenuClick(view: View?) {
        super.onMenuClick(view)
        saveVideo()
    }

    /**
     * 保存视频
     */
    private fun saveVideo() {
        if (!TextUtils.isEmpty(mFromPage) && mTextContent == edit_desc.text.toString()) {
            pop()
            return
        }
        if(TextUtils.isEmpty(mFromPage)) {
            val video = Video()
            video.video_url = mVideoPath
            video.cover_url = mCoverPath
            video.context = edit_desc.text.toString()
            video.create_time = System.currentTimeMillis()
            video.id = System.currentTimeMillis().toString()
            DBHelper.addData(Video::class.java, video)
            val event = Event()
            event.code = Video.CODE_UPDATE
            EventBus.getDefault().post(event)
        } else {
            mVideoList.filter {
                it.id == mVideo?.id
            }.map {
                mVideo?.video_url = mVideoPath
                mVideo?.cover_url = mCoverPath
                mVideo?.context = edit_desc.text.toString()
                mVideo?.create_time = System.currentTimeMillis()
                DBHelper.upDate(Video::class.java, mVideo)
            }
        }
        val view = LayoutInflater.from(activity).inflate(R.layout.view_toast, null)
        val msgText = view.findViewById<TextView>(R.id.txt_message)
        val statusImage = view.findViewById<ImageView>(R.id.img_status)
        msgText.text = "已保存到草稿箱~"
        statusImage.setImageDrawable(resources.getDrawable(R.mipmap.img_publish_success))
        activity.customToast(view)
        Handler().postDelayed({
            pop()
        }, 1000)
    }

}